package com.alm.token.ui.viewpagefragment;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.alm.token.ConStant;
import com.alm.token.R;
import com.alm.token.base.BaseAdapter;
import com.alm.token.base.BaseViewPageFragment;
import com.alm.token.common.RefreshLoadMoreManager;
import com.alm.token.ui.activity.BlockWalletLoginActivity;
import com.alm.token.ui.activity.LogDetailActivity;
import com.alm.token.ui.activity.PayPwdActivity;
import com.alm.token.ui.data.bean.DrawListData;
import com.alm.token.ui.persenter.MyPreenter;
import com.alm.token.ui.view.BaseView;
import com.alm.token.utils.CommonUtil;
import com.alm.token.utils.EmptyUtils;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.BaseViewHolder;

import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.Unbinder;

public class TurnOutListPageFrag extends BaseViewPageFragment implements BaseView<DrawListData> {

    @BindView(R.id.recycler_view)
    RecyclerView recyclerView;
    @BindView(R.id.swipeRefreshLayout)
    SwipeRefreshLayout swipeRefreshLayout;
    @BindView(R.id.tv_clickreload)
    TextView tvClickreload;
    @BindView(R.id.nodatashow_body)
    RelativeLayout nodatashowBody;
    Unbinder unbinder;

    private int limit = 100, page = 1;
    private boolean isfull = false;

    private RefreshLoadMoreManager<DrawListData.DataBeanX.DataBean> manager;

    private List<DrawListData.DataBeanX.DataBean> dataBeans = new ArrayList<>();

    public static TurnOutListPageFrag newInstance() {
        TurnOutListPageFrag fragment = new TurnOutListPageFrag();
        Bundle args = new Bundle();
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    protected MyPreenter initPreenter() {
        return preenter = new MyPreenter(this);
    }

    @Override
    protected int getLayoutId() {
        return R.layout.viewpage_fragment_message_base;
    }

    @Override
    protected void initVariables() {

    }

    @Override
    protected void initViews(View view) {
        initManager();
        swipeRefreshLayout.setVisibility(View.GONE);
    }

    @Override
    public void onClick(View v) {

    }

    private void initManager() {
        MessageAdapter adapter = new MessageAdapter(getActivity());
        manager = new RefreshLoadMoreManager.Builder(getActivity())
                .setAdapter(adapter)
                .setRecyclerView(recyclerView)
                .setOnListItemClickListener(new RefreshLoadMoreManager.OnListItemClickListener() {
                    @Override
                    public void onListItemClick(BaseAdapter.BaseItem item, int position) {
//                        if (dataBeans != null && dataBeans.size() > position) {
//                            Intent intent = new Intent(getContext(), QuantitativeOrderDetailActivity.class);
//                            intent.putExtra("databean", dataBeans.get(position));
//                            startActivity(intent);
//                        }

                    }
                })
                .setSwipeRefreshLayout(swipeRefreshLayout)
                .setOnRefreshListener(new RefreshLoadMoreManager.OnRefreshListener() {
                    @Override
                    public void onRefresh() {
//                        showToast("onRefresh");
                        swipeRefreshLayout.setRefreshing(false);
                        loadData();
                    }
                })
                .setOpenLoadMore(true)
                .setOnLoadMoreListener(new RefreshLoadMoreManager.OnLoadMoreListener() {
                    @Override
                    public void onLoadMore() {

                        manager.getAdapter().loadMoreEnd(true);
                        manager.getAdapter().loadMoreFail();
                        showWaitDialog();
                        preenter.getDrawListData(String.valueOf(limit), String.valueOf(page));
                    }
                })

                .build();
        adapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                if (EmptyUtils.isNotEmpty(dataBeans) && dataBeans.size() > position) {
                    Intent intent = new Intent(getActivity(), LogDetailActivity.class);
                    intent.putExtra("LogDetailActivity_type", LogDetailActivity.DRAW_TYPE);
                    intent.putExtra("LogDetailActivity_id", dataBeans.get(position).getId());
                    startActivity(intent);
                }
            }
        });
    }

    @Override
    protected void loadData() {
        limit = 100;
        page = 1;
        preenter.getDrawListData(String.valueOf(limit), String.valueOf(page));
    }

    @Override
    public void onResume() {
        super.onResume();
    }

    @Override
    public void jumpToLoginAct(int staue) {
        if (staue == 3) {
//            showToast("需要重新登录!");
//            showToast(getString(R.string.common_relogin));
//            Intent intent = new Intent();
//            intent.setAction(ConStant.EXIT_APP);
//            getActivity().sendBroadcast(intent);
//            startActivity(BlockWalletLoginActivity.class);
//            getActivity().finish();
        } else if (staue == 4) {
//            showToast(getString(R.string.paypasw_hint_setpaypsw));
//            Intent intent = new Intent(getActivity(),PayPwdActivity.class);
//            intent.putExtra("PayPwdActivityType",PayPwdActivity.PAYPSW_SET);
//            startActivity(intent);
//            getActivity().finish();
            showToSetPaypswDialog();
        }else if (staue == 666) {
            showToUpdata();
        }
    }

    private List<DrawListData.DataBeanX.DataBean> dataBeansOld = new ArrayList<>();

    @Override
    public void getData(DrawListData drawListData) {

        if (drawListData.getStatus() == 0 && drawListData.getData() != null && drawListData.getData().getData() != null) {


            if (page == 1) {
                dataBeans.clear();
            } else if (!isfull && dataBeans.size() > (page - 1) * 100) {
                dataBeans.removeAll(dataBeansOld);
            }

            if (drawListData.getData().getData().size() == 100) {
                isfull = true;
                page = page + 1;
            } else {
                isfull = false;
            }

            dataBeansOld = drawListData.getData().getData();
            for (int i = 0; i < dataBeansOld.size(); i++) {
                dataBeansOld.get(i).setLayoutId(MessageAdapter.LAYOUT_ID);
            }
            dataBeans.addAll(dataBeansOld);

            manager.setData(dataBeans);
        } else showToast(drawListData.getMsg());
        if (dataBeans.size() == 0) {
            swipeRefreshLayout.setVisibility(View.GONE);
            nodatashowBody.setVisibility(View.VISIBLE);
        } else {
            swipeRefreshLayout.setVisibility(View.VISIBLE);
            nodatashowBody.setVisibility(View.GONE);
        }
    }

    @Override
    public void onError(String error) {

        showToast(getString(R.string.common_loaderrritry));
    }

    @Override
    public void ShowProgress() {

        showWaitDialog();
    }

    @Override
    public void hideProgress() {

        hideWaitDialog();
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        // TODO: inflate a fragment view
        View rootView = super.onCreateView(inflater, container, savedInstanceState);
        unbinder = ButterKnife.bind(this, rootView);
        return rootView;
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        unbinder.unbind();
    }

    @OnClick(R.id.tv_clickreload)
    public void onViewClicked() {
        loadData();
    }


    public class MessageAdapter extends BaseAdapter<DrawListData.DataBeanX.DataBean> {

        public static final int LAYOUT_ID = R.layout.item_transformlist_base;

        public MessageAdapter(@NonNull Context context) {
            super(context);
        }

        @Override
        protected void convert(BaseViewHolder helper, DrawListData.DataBeanX.DataBean item, int itemType) {
            /**
             * id : 20
             * userId : 111
             * userName : test2
             * userPhone : 15006610057
             * orderSn : 12916541023
             * totalMoney : 1
             * money : 2
             * moneyType : 1
             * pro : 1
             * proMoney : 1
             * token : 0x708390B941b9DbaA74aBc66e34826cF2028Ea872
             * payStatus : 1
             * createTime : 1546657366000
             * updateTime : 1546657358000
             * endTime : null
             * status : 2
             * msg :
             * failMsg :
             * content :
             * proMoneyType : 2
             * txhash : null
             * lohasUser : null
             * statusStr : 处理中
             * payStatusStr : 成功
             * moneyTypeStr : ETH
             * proMoneyTypeStr : G12
             */


            TextView textView = helper.getView(R.id.tv_name0);
            textView.setMaxLines(4);
            textView.setTextSize(12);
            String adress = item.getToken() != null && !item.getToken().isEmpty() ? item.getToken() : " ";
            if (adress != null && adress.length() > 45) {
                adress = adress.substring(0, 41);
            }

//            String adress = item.getToken() != null && !item.getToken().isEmpty() ? item.getToken().substring(0, item.getToken().length() / 4) : " ";
            textView.setText(adress);

            helper.setText(R.id.tv_staue, "" + item.getStatusStr());
            helper.setText(R.id.tv_phone0, "" + CommonUtil.saveToPoint4WithNo(item.getTotalMoney()) + item.getMoneyTypeStr());
            if (item.getUpdateTime() != 0) {
                helper.setText(R.id.tv_time0, "" + CommonUtil.getDateTimeFromMillisecond(item.getUpdateTime()));
            } else {
                helper.setText(R.id.tv_time0, "" + CommonUtil.getDateTimeFromMillisecond(item.getCreateTime()));
            }

//            TextView textView1 = helper.getView(R.id.message);
//            textView1.setTextSize(15);
//
//            textView1.setText("支付" + item.getMoneyTypeStr() + ":" + item.getPayStatusStr()
//                    + "  接收" + item.getProMoneyTypeStr() + "\n" + "订单状态:" + item.getStatusStr() + "  数量:" + item.getTotalMoney());
//
//
//            TextView date = helper.getView(R.id.date);
//            date.setMaxLines(2);
//            TextView enddate = helper.getView(R.id.date_end);
//            date.setMaxLines(2);
//            date.setText("\n" + CommonUtil.getDateTimeFromMillisecond(item.getCreateTime()).split(" ")[0]);
//            if (item.getEndTime() != 0L) {
//                helper.setVisible(R.id.date_end, true);
//                enddate.setText("\n" + CommonUtil.getDateTimeFromMillisecond(item.getEndTime()).split(" ")[0]);
//            } else {
//                helper.setVisible(R.id.date_end, false);
////                helper.setText(R.id.date_end, CommonUtil.getDateTimeFromMillisecond(item.getUpdateTime()).split(" ")[0]);
//            }
        }

    }
}
